<?php
abstract class CacheBase extends Object
{
    protected $cacheFile;
    protected $cacheHour;
    protected $cachable;

    public function CacheBase($hour, $file)
    {
        $this->cacheHour = $hour;
        $this->cacheFile = $file;
        $this->cachable = $this->cacheHour > 0;
    }

    abstract public function Render();

    abstract public function Save($content);

    protected function IsExisted()
    {
        return file_exists($this->cacheFile);
    }

    public function IsValid()
    {
        if (!$this->cachable) return false;

        return $this->IsExisted()
            && !self::IsExpired($this->cacheFile, $this->cacheHour)
            && !AppConfig::GetInstance()->IsClearCache();
    }

    public static function IsExpired($file, $hour)
    {
        return time() - filemtime($file) > $hour * 3600;
    }

    public static function CleanUpAll()
    {
        $cache_items = SettingModel::GetInstance()->GetCaches();

        $count = 0;
        foreach ($cache_items as $key => $hour)
        {
            $count += self::CleanUp($key, $hour);
        }
        MessageBase::Confirm("Total files removed: $count");
    }

    public static function CleanUp($key, $hour)
    {
        $keys = explode('.', $key);
        if (count($keys) < 3)
        {
            return self::CleanUpPath($keys[1], $hour);
        }

        $controller = $keys[1];
        $action = $keys[2];
        $countries = FileHandler::GetSubDirs(AppConfig::GetInstance()->DIR_CACHE);

        $count = 0;
        foreach ($countries as $country)
        {
            $count += self::CleanUpPath($country.DS.$controller.DS.$action, $hour);
        }
        return $count;
    }

    public static function CleanUpPath($path, $hour)
    {
        $path = AppConfig::GetInstance()->DIR_CACHE.DS.$path;
        if (!file_exists($path))
            return;

        $count = 0;
        $files = FileHandler::GetSubs($path);
        foreach ($files as $file)
        {
            $file = $path.DS.$file;
            if (self::IsExpired($file, $hour))
            {
                FileHandler::Remove($file);
                MessageBase::Confirm('removed: '.$filepath);
                $count++;
            }
        }
        return $count;
    }

    public function IsCachable()
    {
        return $this->cachable;
    }
}
?>